package com.business.dashboard.controller;

import com.business.dashboard.service.AdminUserService;
import com.business.dashboard.service.UserService;
import com.business.dashboard.utils.ResultUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.sql.DataSource;
import java.sql.Connection;
import java.util.HashMap;
import java.util.Map;

/**
 * 系统健康检查控制器
 *
 * @author Claude
 * @since 2025-07-06
 */
@Slf4j
@RestController
@RequestMapping("/api/health")
public class HealthController {

    @Autowired
    private DataSource dataSource;

    @Autowired
    private AdminUserService adminUserService;

    @Autowired
    private UserService userService;

    /**
     * 系统健康检查
     */
    @GetMapping("")
    public ResultUtil<Map<String, Object>> health() {
        Map<String, Object> healthStatus = new HashMap<>();
        boolean allHealthy = true;

        try {
            // 基础系统信息
            healthStatus.put("application", "business-dashboard-master");
            healthStatus.put("status", "运行中");
            healthStatus.put("timestamp", System.currentTimeMillis());
            healthStatus.put("javaVersion", System.getProperty("java.version"));
            healthStatus.put("springProfile", System.getProperty("spring.profiles.active", "default"));

            // 检查数据库连接
            try (Connection connection = dataSource.getConnection()) {
                healthStatus.put("database", "健康");
                healthStatus.put("dbUrl", maskPassword(connection.getMetaData().getURL()));
                healthStatus.put("dbDriver", connection.getMetaData().getDriverName());
                log.info("数据库连接检查: 正常");
            } catch (Exception e) {
                healthStatus.put("database", "异常");
                healthStatus.put("dbError", e.getMessage());
                allHealthy = false;
                log.warn("数据库连接检查: 失败 - {}", e.getMessage());
            }

            // 检查用户服务 (如果数据库可用)
            if (allHealthy) {
                try {
                    long userCount = userService.getUserCount();
                    healthStatus.put("userService", "健康");
                    healthStatus.put("userCount", userCount);
                    log.debug("用户服务检查: 正常，用户数: {}", userCount);
                } catch (Exception e) {
                    healthStatus.put("userService", "异常");
                    healthStatus.put("userServiceError", e.getMessage());
                    allHealthy = false;
                    log.warn("用户服务检查: 失败 - {}", e.getMessage());
                }

                try {
                    adminUserService.getAllUsers();
                    healthStatus.put("adminService", "健康");
                    log.debug("管理员服务检查: 正常");
                } catch (Exception e) {
                    healthStatus.put("adminService", "异常");
                    healthStatus.put("adminServiceError", e.getMessage());
                    allHealthy = false;
                    log.warn("管理员服务检查: 失败 - {}", e.getMessage());
                }
            } else {
                healthStatus.put("userService", "跳过 (数据库异常)");
                healthStatus.put("adminService", "跳过 (数据库异常)");
            }

            // 内存使用情况
            Runtime runtime = Runtime.getRuntime();
            Map<String, Object> memory = new HashMap<>();
            memory.put("total", runtime.totalMemory());
            memory.put("free", runtime.freeMemory());
            memory.put("used", runtime.totalMemory() - runtime.freeMemory());
            memory.put("max", runtime.maxMemory());
            healthStatus.put("memory", memory);

            String message = allHealthy ? "系统健康检查完成，所有组件正常" : "系统健康检查完成，发现异常组件";
            return allHealthy ?
                ResultUtil.success(message, healthStatus) :
                ResultUtil.error(message, healthStatus);

        } catch (Exception e) {
            log.error("健康检查过程发生异常", e);
            healthStatus.put("error", e.getMessage());
            healthStatus.put("errorType", e.getClass().getSimpleName());
            return ResultUtil.error("健康检查失败", healthStatus);
        }
    }

    /**
     * 屏蔽密码信息
     */
    private String maskPassword(String url) {
        if (url == null) return null;
        return url.replaceAll("password=[^&]+", "password=***");
    }

    /**
     * 数据库连接测试
     */
    @GetMapping("/db")
    public ResultUtil<Map<String, Object>> dbTest() {
        Map<String, Object> result = new HashMap<>();

        try (Connection connection = dataSource.getConnection()) {
            result.put("connected", true);
            result.put("url", connection.getMetaData().getURL());
            result.put("driver", connection.getMetaData().getDriverName());
            result.put("version", connection.getMetaData().getDatabaseProductVersion());

            return ResultUtil.success("数据库连接正常", result);
        } catch (Exception e) {
            log.error("数据库连接测试失败", e);
            result.put("connected", false);
            result.put("error", e.getMessage());
            return ResultUtil.error("数据库连接失败", result);
        }
    }

}